import React, { useState, useEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSearch, faTimes } from '@fortawesome/free-solid-svg-icons'
import useKeyPress from '../hooks/useKeyPress'
import './FileSearch.scss'
const FileSearch = ({ title, onFileSearch }) => {
    const [ inputActive, setInputActive ] = useState(false) 
    const [ value, setValue ] = useState('')
    const enterPressed = useKeyPress(13)
    const escPressed = useKeyPress(27)
    let node = useRef(null)
    const closeSearch = () => {
        setInputActive(false)
        setValue('')
        onFileSearch('')
    }
    useEffect(() => {
        if(enterPressed && inputActive) {
            onFileSearch(value)
        }
        if(escPressed && inputActive) {
            closeSearch()
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [enterPressed, escPressed])
    useEffect(() => {
        if(inputActive) {
            node.current.focus()
        }
    }, [inputActive])
    return (
        <div className="alert-primary file-search-box p-2">
            { !inputActive &&
             <div className="d-flex justify-content-between align-items-center">
                 <span>{title}</span>
                 <button type="button" className="p-0 btn icon-button btn-sm btn-primary" onClick={ () => {setInputActive(true)}}>
                    <FontAwesomeIcon title="搜索" icon={faSearch} />
                 </button>
             </div>
            }
            {
                inputActive && 
                <div className="d-flex justify-content-between align-items-center input-group-sm">
                    <input ref={node} className="form-control" value={value} onChange={(e) => {setValue(e.target.value)}}/>
                    <button type="button" className="ml-2 p-0 btn icon-button btn-sm btn-primary mgl6" onClick={ closeSearch }>
                        <FontAwesomeIcon size="sm" title="关闭" icon={faTimes} />
                    </button>
                </div>
            }
        </div>
    )
}
FileSearch.propTypes = {
    title: PropTypes.string,
    onFileSearch: PropTypes.func.isRequired
}
FileSearch.defaultProps = {
    title: '我的云文档'
}
export default FileSearch